document.addEventListener('DOMContentLoaded', function () {
    const loginForm = document.getElementById('loginForm');
    const registerForm = document.getElementById('registerForm');
    const logoutButton = document.getElementById('logoutButton');
    const welcomeMessage = document.getElementById('welcomeMessage');
    const errorMessage = document.getElementById('errorMessage');

    if (loginForm) {
        loginForm.style.opacity = 0;
        setTimeout(() => {
            loginForm.style.opacity = 1;
            loginForm.style.transform = 'translateY(0)';
        }, 200);

        loginForm.addEventListener('submit', async (e) => {
            e.preventDefault();
            const username = document.getElementById('username').value;
            const password = document.getElementById('password').value;
            const data = {
                username: username,
                password: password
            };
            try {
                const response = await fetch('/login', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify(data)
                });
                const result = await response.json();
                if (response.ok) {
                    const token = result.token;
                    localStorage.setItem('token', token);
                    // 直接在当前页面加载仪表盘内容
                    const dashboardResponse = await fetch('/dashboard', {
                        method: 'GET',
                        headers: {
                            'Authorization': `Bearer ${token}`
                        }
                    });
                    if (dashboardResponse.ok) {
                        const dashboardHtml = await dashboardResponse.text();
                        document.open();
                        document.write(dashboardHtml);
                        document.close();
                    } else {
                        const dashboardError = await dashboardResponse.json();
                        errorMessage.textContent = dashboardError.error;
                    }
                } else {
                    errorMessage.textContent = result.error;
                }
            } catch (error) {
                errorMessage.textContent = '请求出错: ' + error.message;
            }
        });
    }

    if (registerForm) {
        registerForm.style.opacity = 0;
        setTimeout(() => {
            registerForm.style.opacity = 1;
            registerForm.style.transform = 'translateY(0)';
        }, 200);

        registerForm.addEventListener('submit', async (e) => {
            e.preventDefault();
            const username = document.getElementById('username').value;
            const password = document.getElementById('password').value;
            const data = {
                username: username,
                password: password
            };
            try {
                const response = await fetch('/register', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify(data)
                });
                const result = await response.json();
                if (response.ok) {
                    window.location.href = '/login';
                } else {
                    errorMessage.textContent = result.error;
                }
            } catch (error) {
                errorMessage.textContent = '请求出错: ' + error.message;
            }
        });
    }

    if (logoutButton) {
        logoutButton.addEventListener('click', () => {
            localStorage.removeItem('token');
            window.location.href = '/login';
        });
    }

    if (welcomeMessage) {
        const token = localStorage.getItem('token');
        if (token) {
            const payload = JSON.parse(atob(token.split('.')[1]));
            welcomeMessage.textContent = `欢迎，${payload.username}！你是 ${payload.role}。`;
        } else {
            window.location.href = '/login';
        }
    }

    // 移除页面加载时的请求逻辑
    // window.addEventListener('load', async () => {
    //     const token = localStorage.getItem('token');
    //     if (token) {
    //         try {
    //             const response = await fetch('/dashboard', {
    //                 method: 'GET',
    //                 headers: {
    //                     'Authorization': `Bearer ${token}`
    //                 }
    //             });
    //             if (response.ok) {
    //                 const dashboardHtml = await response.text();
    //                 document.open();
    //                 document.write(dashboardHtml);
    //                 document.close();
    //             } else {
    //                 const dashboardError = await response.json();
    //                 errorMessage.textContent = dashboardError.error;
    //             }
    //         } catch (error) {
    //             errorMessage.textContent = '请求出错: ' + error.message;
    //         }
    //     }
    // });
});